package au.csiro.nt.psdp.actions;

import com.opensymphony.xwork2.ActionSupport;
import au.csiro.nt.psdp.actions.util.PdspConstants;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.HashMap;

import org.apache.struts2.ServletActionContext;
import org.appfuse.Constants;
import org.appfuse.util.StringUtil;

public class PdspActionSupport extends ActionSupport
{
    public static final String CANCEL = "cancel";

    /**
     * Convenience method to get the Configuration HashMap
     * from the servlet context.
     *
     * @return the user's populated form from the session
     */
    protected Map getConfiguration()
    {
        Map config = (HashMap) getSession().getServletContext().getAttribute(PdspConstants.CONFIG);
        // so unit tests don't puke when nothing's been set
        if (config == null)
        {
            return new HashMap();
        }
        return config;
    }

    /**
     * Convenience method to get the request
     *
     * @return current request
     */
    protected HttpServletRequest getRequest()
    {
        return ServletActionContext.getRequest();
    }

    /**
     * Convenience method to get the response
     *
     * @return current response
     */
    protected HttpServletResponse getResponse()
    {
        return ServletActionContext.getResponse();
    }

    /**
     * Convenience method to get the session. This will create a session if one doesn't exist.
     *
     * @return the session from the request (request.getSession()).
     */
    protected HttpSession getSession()
    {
        return getRequest().getSession();
    }

    protected String encryptPassword(String password)
    {
        Boolean encrypt = (Boolean) getConfiguration().get(Constants.ENCRYPT_PASSWORD);
        if ("true".equals(getRequest().getParameter("encryptPass")) && (encrypt != null && encrypt))
        {
            String algorithm = (String) getConfiguration().get(Constants.ENC_ALGORITHM);

            if (algorithm == null)
            { // should only happen for test case
                //log.debug("assuming testcase, setting algorithm to 'SHA'");
                algorithm = "SHA";
            }

            return StringUtil.encodePassword(password, algorithm);
        }
        return password;
    }

    protected Map buildMap(Object k1, Object v1)
    {
    	Map map = new HashMap();
    	map.put(k1, v1);
    	return map;
    }

    protected List buildList(Object o1)
    {
    	List list = new ArrayList();
    	list.add(o1);
    	return list;
    }
}
